package org.thingsboard.server.dao.sql.schedulerEvent;

import com.google.common.util.concurrent.ListenableFuture;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Component;
import org.thingsboard.server.common.data.EntitySubtype;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.SchedulerEvent;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.dao.model.sql.SchedulerEventEntity;
import org.thingsboard.server.dao.schedulerEvent.SchedulerEventDao;
import org.thingsboard.server.dao.sql.JpaAbstractSearchTextDao;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

@Component
public class JpaSchedulerEventDao extends JpaAbstractSearchTextDao<SchedulerEventEntity, SchedulerEvent> implements SchedulerEventDao {
    @Autowired
    SchedulerEventRepository schedulerEventRepository;
    @Override
    public Long countByTenantId(TenantId tenantId) {
        return schedulerEventRepository.countByTenantId(tenantId.getId());
    }

    @Override
    protected Class<SchedulerEventEntity> getEntityClass() {
        return SchedulerEventEntity.class;
    }

    @Override
    protected CrudRepository<SchedulerEventEntity, UUID> getCrudRepository() {
        return schedulerEventRepository;
    }


    @Override
    public ListenableFuture<List<EntitySubtype>> findTenantSchedulerEventTypesAsync(UUID tenantId) {
        return service.submit(() -> convertTenantSchedulerEventTypesToDto(tenantId, schedulerEventRepository.findSchedulerEventTypes(tenantId)));
    }



    private List<EntitySubtype> convertTenantSchedulerEventTypesToDto(UUID tenantId, List<String> types) {
        List<EntitySubtype> list = Collections.emptyList();
        if (types != null && !types.isEmpty()) {
            list = new ArrayList<>();
            for (String type : types) {
                list.add(new EntitySubtype(new TenantId(tenantId), EntityType.DEVICE, type));
            }
        }
        return list;
    }
}
